package cn.hjh.util;




import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory factory;

    //静态代码块
    static {
        try {
            //定义核心配置文件名称
            String resource = "mybatis-config.xml";

            //读取配置文件
            InputStream is = Resources.getResourceAsStream(resource);

            //创建SqlSessionFactory
            factory = new SqlSessionFactoryBuilder().build(is);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public  static SqlSession createSqlSession(){
        return factory.openSession();
    }

    public static void closeSqlSession(SqlSession sqlSession){
        if (null != sqlSession){
            sqlSession.close();
        }
    }

}
